package com.api.demo.controller;

import com.api.demo.entity.User;
import com.api.demo.service.FileService;
import com.api.demo.service.UserService;
import com.api.demo.util.JwtUtil;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/users")
@CrossOrigin(origins = "*", allowedHeaders = "*")
public class UserController {

    @Autowired
    private UserService userService;
    
    @Autowired
    private FileService fileService;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @PostMapping("/avatar")
    public ResponseEntity<?> uploadAvatar(@RequestHeader(value = "Authorization", required = false) String token,
                                         @RequestParam("file") MultipartFile file) {
        System.out.println("收到头像上传请求: " + file.getOriginalFilename() + ", 大小: " + file.getSize() + " bytes");
        
        try {
            // 存储文件
            System.out.println("开始存储文件...");
            String avatarUrl = fileService.storeAvatar(file);
            System.out.println("文件存储成功，URL: " + avatarUrl);
            
            // 如果有token，则更新用户头像
            if (token != null && token.startsWith("Bearer ")) {
                System.out.println("检测到token，尝试更新用户头像");
                token = token.substring(7);
                
                if (jwtUtil.validateToken(token)) {
                    String username = jwtUtil.getUsernameFromToken(token);
                    User user = userService.findByUsername(username);
                    
                    if (user != null) {
                        boolean updated = userService.updateAvatar(user.getId(), avatarUrl);
                        System.out.println("用户头像更新" + (updated ? "成功" : "失败") + ": " + username);
                    } else {
                        System.out.println("用户不存在");
                    }
                } else {
                    System.out.println("无效的token");
                }
            } else {
                System.out.println("没有提供token，仅返回上传的文件URL");
            }
            
            // 返回成功响应
            Map<String, Object> response = new HashMap<>();
            response.put("message", "头像上传成功");
            response.put("avatarUrl", avatarUrl);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            System.err.println("头像上传失败: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.badRequest().body(new MessageResponse("头像上传失败: " + e.getMessage()));
        }
    }
    
    @Data
    public static class MessageResponse {
        private String message;

        public MessageResponse(String message) {
            this.message = message;
        }
    }
} 